﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Collections;
using System.Globalization;
using System.Web.Mvc.Html;

namespace GameSchool.HtmlHelpers
{
    /// <summary>
    /// Þessi helper var fenginn af: http://stackoverflow.com/questions/9511323/variation-on-adding-html-attributes-to-html-beginform
    /// </summary>
    public static class FormExtensions
    {
        private static object _lastFormNumKey = new object();

        public static IDisposable BeginForm(this HtmlHelper htmlHelper, object htmlAttributes)
        {
            string rawUrl = htmlHelper.ViewContext.HttpContext.Request.RawUrl;
            return htmlHelper.FormHelper(rawUrl, FormMethod.Post, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
        }

        private static int IncrementFormCount(IDictionary items)
        {
            object obj2 = items[_lastFormNumKey];
            int num = (obj2 != null) ? (((int)obj2) + 1) : 0;
            items[_lastFormNumKey] = num;
            return num;
        }

        private static string DefaultFormIdGenerator(this HtmlHelper htmlhelper)
        {
            int num = IncrementFormCount(htmlhelper.ViewContext.HttpContext.Items);
            return string.Format(CultureInfo.InvariantCulture, "form{0}", new object[] { num });
        }

        private static IDisposable FormHelper(this HtmlHelper htmlHelper, string formAction, FormMethod method, IDictionary<string, object> htmlAttributes)
        {
            var builder = new TagBuilder("form");
            builder.MergeAttributes<string, object>(htmlAttributes);
            builder.MergeAttribute("action", formAction);
            builder.MergeAttribute("method", HtmlHelper.GetFormMethodString(method), true);
            bool flag = htmlHelper.ViewContext.ClientValidationEnabled && !htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled;
            if (flag)
            {
                builder.GenerateId(htmlHelper.DefaultFormIdGenerator());
            }
            htmlHelper.ViewContext.Writer.Write(builder.ToString(TagRenderMode.StartTag));
            var form = new System.Web.Mvc.Html.MvcForm(htmlHelper.ViewContext);
            if (flag)
            {
                htmlHelper.ViewContext.FormContext.FormId = builder.Attributes["id"];
            }
            return form;
        }
    }
}